<template>
  <div class="w-full max-w-md">
    <!-- 表单标题 -->
    <div class="text-center mb-8">
      <h2 class="text-3xl font-bold text-gray-800 mb-2">
        {{ mode === 'login' ? '欢迎回来' : '创建账号' }}
      </h2>
      <p class="text-gray-600">
        {{ mode === 'login' ? '登录到你的账号' : '开始你的写作之旅' }}
      </p>
    </div>

    <!-- 表单 -->
    <form @submit.prevent="handleSubmit" class="space-y-6">
      <!-- 用户名输入 -->
      <div>
        <label for="username" class="block text-sm font-medium text-gray-700 mb-2">
          <User class="inline w-4 h-4 mr-1" />
          用户名
        </label>
        <input
          id="username"
          v-model="formData.username"
          type="text"
          placeholder="请输入用户名 (3-20字符)"
          class="w-full px-4 py-3 rounded-lg border border-gray-200 focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
          :class="{ 'border-red-400': errors.username }"
          @blur="validateField('username')"
          @input="clearError('username')"
        />
        <p v-if="errors.username" class="mt-1 text-sm text-red-400">
          {{ errors.username }}
        </p>
      </div>

      <!-- 密码输入 -->
      <div>
        <label for="password" class="block text-sm font-medium text-gray-700 mb-2">
          <Lock class="inline w-4 h-4 mr-1" />
          密码
        </label>
        <div class="relative">
          <input
            id="password"
            v-model="formData.password"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码 (6-20字符)"
            class="w-full px-4 py-3 rounded-lg border border-gray-200 focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all pr-10"
            :class="{ 'border-red-400': errors.password }"
            @blur="validateField('password')"
            @input="clearError('password')"
          />
          <button
            type="button"
            @click="showPassword = !showPassword"
            class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
          >
            <Eye v-if="!showPassword" class="w-5 h-5" />
            <EyeOff v-else class="w-5 h-5" />
          </button>
        </div>
        <p v-if="errors.password" class="mt-1 text-sm text-red-400">
          {{ errors.password }}
        </p>
      </div>

      <!-- 学段选择 (仅注册时显示) -->
      <div v-if="mode === 'register'">
        <label class="block text-sm font-medium text-gray-700 mb-2">
          <GraduationCap class="inline w-4 h-4 mr-1" />
          选择学段
        </label>
        <div class="grid grid-cols-3 gap-3">
          <button
            v-for="level in gradeLevels"
            :key="level.value"
            type="button"
            @click="formData.gradeLevel = level.value"
            class="py-3 px-4 rounded-lg font-medium transition-all"
            :class="
              formData.gradeLevel === level.value
                ? 'bg-blue-500 text-white shadow-md'
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            "
          >
            {{ level.label }}
          </button>
        </div>
        <p v-if="errors.gradeLevel" class="mt-1 text-sm text-red-400">
          {{ errors.gradeLevel }}
        </p>
      </div>

      <!-- 错误提示 -->
      <div v-if="globalError" class="p-4 rounded-lg bg-red-50 border border-red-200">
        <div class="flex items-start">
          <AlertCircle class="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" />
          <p class="ml-3 text-sm text-red-700">{{ globalError }}</p>
        </div>
      </div>

      <!-- 提交按钮 -->
      <button
        type="submit"
        :disabled="loading"
        class="w-full py-3 px-4 rounded-lg font-medium text-white transition-all"
        :class="
          loading
            ? 'bg-gray-300 cursor-not-allowed'
            : 'bg-blue-500 hover:bg-blue-600 shadow-md hover:shadow-lg'
        "
      >
        <span v-if="loading" class="flex items-center justify-center">
          <Loader class="w-5 h-5 mr-2 animate-spin" />
          {{ mode === 'login' ? '登录中...' : '注册中...' }}
        </span>
        <span v-else>
          {{ mode === 'login' ? '登录' : '注册' }}
        </span>
      </button>
    </form>

    <!-- 切换链接 -->
    <div class="mt-6 text-center">
      <p class="text-sm text-gray-600">
        {{ mode === 'login' ? '还没有账号？' : '已有账号？' }}
        <button
          type="button"
          @click="$emit('toggle-mode')"
          class="text-blue-500 hover:text-blue-600 font-medium ml-1"
        >
          {{ mode === 'login' ? '立即注册' : '立即登录' }}
        </button>
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { User, Lock, Eye, EyeOff, GraduationCap, AlertCircle, Loader } from 'lucide-vue-next';

const props = defineProps({
  mode: {
    type: String,
    required: true,
    validator: (value) => ['login', 'register'].includes(value),
  },
  loading: {
    type: Boolean,
    default: false,
  },
  error: {
    type: String,
    default: '',
  },
});

const emit = defineEmits(['submit', 'toggle-mode']);

// 表单数据
const formData = reactive({
  username: '',
  password: '',
  gradeLevel: 'middle', // 默认初中
});

// 表单验证错误
const errors = reactive({
  username: '',
  password: '',
  gradeLevel: '',
});

// 密码显示控制
const showPassword = ref(false);

// 全局错误（来自props）
const globalError = computed(() => props.error);

// 学段选项
const gradeLevels = [
  { value: 'primary', label: '小学' },
  { value: 'middle', label: '初中' },
  { value: 'high', label: '高中' },
];

/**
 * 验证单个字段
 */
const validateField = (field) => {
  errors[field] = '';

  switch (field) {
    case 'username':
      if (!formData.username) {
        errors.username = '请输入用户名';
      } else if (formData.username.length < 3) {
        errors.username = '用户名至少3个字符';
      } else if (formData.username.length > 20) {
        errors.username = '用户名最多20个字符';
      } else if (!/^[a-zA-Z0-9_]+$/.test(formData.username)) {
        errors.username = '用户名只能包含字母、数字和下划线';
      }
      break;

    case 'password':
      if (!formData.password) {
        errors.password = '请输入密码';
      } else if (formData.password.length < 6) {
        errors.password = '密码至少6个字符';
      } else if (formData.password.length > 20) {
        errors.password = '密码最多20个字符';
      }
      break;

    case 'gradeLevel':
      if (props.mode === 'register' && !formData.gradeLevel) {
        errors.gradeLevel = '请选择学段';
      }
      break;
  }
};

/**
 * 清除单个字段的错误
 */
const clearError = (field) => {
  errors[field] = '';
};

/**
 * 验证整个表单
 */
const validateForm = () => {
  // 验证所有字段
  validateField('username');
  validateField('password');
  if (props.mode === 'register') {
    validateField('gradeLevel');
  }

  // 检查是否有错误
  return !Object.values(errors).some((error) => error !== '');
};

/**
 * 处理表单提交
 */
const handleSubmit = () => {
  // 验证表单
  if (!validateForm()) {
    return;
  }

  // 准备提交数据
  const submitData = {
    username: formData.username,
    password: formData.password,
  };

  // 注册模式包含学段
  if (props.mode === 'register') {
    submitData.gradeLevel = formData.gradeLevel;
  }

  // 触发提交事件
  emit('submit', submitData);
};

/**
 * 重置表单
 */
const resetForm = () => {
  formData.username = '';
  formData.password = '';
  formData.gradeLevel = 'middle';
  Object.keys(errors).forEach((key) => {
    errors[key] = '';
  });
  showPassword.value = false;
};

// 暴露方法供父组件调用
defineExpose({
  resetForm,
});
</script>

<style scoped>
/* 自定义样式（如果需要） */
</style>

